import React, { Component } from 'react';
import { navigate } from 'utils/router';
import { Button, Balloon, Result, ConfigProvider } from '@teamix/ui';
import { ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import UnfreezeIpModal from 'components/unfreezeIpModal';
import intl from '../../locale';

export default class Error extends Component {
  state = {
    // 关闭白名单验证的弹窗
    isModalOpen: false,
  };

  renderDesc = () => {
    const { errorAction, errorTraceId } = this.props;
    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: errorAction }} />
        {errorTraceId ? <div style={{ color: '#f0f0f0' }}>traceId: {errorTraceId}</div> : null}
      </div>
    );
  };

  renderBtns = () => {
    // 访问IP受限，需要关闭IP验证
    const { errorCode, errorMessage } = this.props;
    const { organization } = window.FORCE;
    const isOrgAdmin = access(ORGANIZATION_ADMIN_ROLES, organization.user_role);
    const { user } = window.FORCE;
    let btn;
    switch (errorCode) {
      case 'FORBIDDEN':
        btn = [
          <Button
            type="normal"
            onClick={() => {
              window.history.go(-1);
            }}
          >
            {intl.get({
              id: 'code-assets.components.errorPage.ReturnToPreviousPage',
              defaultMessage: '返回上一页',
            })}
          </Button>,
          isOrgAdmin &&
            errorMessage ===
              intl.get({
                id: 'code-assets.components.errorPage.RestrictedAccessIpAddress',
                defaultMessage: '访问IP受限',
              }) &&
            (user.email ? (
              <Button
                type="primary"
                onClick={() => {
                  this.setState({ isModalOpen: true });
                }}
              >
                {intl.get({
                  id: 'code-assets.components.errorPage.DisableIpWhitelistVerification',
                  defaultMessage: '关闭 IP 白名单验证',
                })}
              </Button>
            ) : (
              <Balloon.Tooltip
                align="t"
                trigger={
                  <Button type="primary" disabled>
                    {intl.get({
                      id: 'code-assets.components.errorPage.DisableIpWhitelistVerification',
                      defaultMessage: '关闭 IP 白名单验证',
                    })}
                  </Button>
                }
              >
                {intl.get({
                  id: 'code-assets.components.errorPage.ToRegisterAnEmailAddress',
                  defaultMessage:
                    '需登记邮箱验证，请点击右上角「头像」- 「个人设置」绑定主邮箱后重试',
                })}
              </Balloon.Tooltip>
            )),
        ];

        break;
      // FIXME 待后端修复这个errorCode
      case 'invalid session':
      case 'SESSION_INVALID':
        btn = [
          <Button
            type="normal"
            onClick={() => {
              // 待确定
              window.location.href = 'https://codeup.aliyun.com';
            }}
          >
            {intl.get({
              id: 'code-assets.components.errorPage.LogOnAgain',
              defaultMessage: '重新登录',
            })}
          </Button>,
        ];
        break;
      default:
        btn = [
          <Button
            type="normal"
            onClick={() => {
              window.history.go(-1);
            }}
          >
            {intl.get({
              id: 'code-assets.components.errorPage.ReturnToPreviousPage',
              defaultMessage: '返回上一页',
            })}
          </Button>,
          <Button
            type="primary"
            onClick={() => {
              navigate('/');
            }}
          >
            {intl.get({
              id: 'code-assets.components.errorPage.ReturnToHomePage',
              defaultMessage: '返回首页',
            })}
          </Button>,
        ];

        break;
    }

    return btn;
  };

  render() {
    const { errorMessage, errorCode, errorAction, errorTraceId, ...others } = this.props;
    const { isModalOpen } = this.state;

    let status;
    switch (errorCode) {
      case 'SYSTEM_ERROR':
        status = '500';
        break;
      case 'FORBIDDEN':
        status = '403';
        break;
      case 'NOT_FOUND':
        status = '404';
        break;
      // FIXME 待后端修复这个errorCode
      case 'invalid session':
      case 'SESSION_INVALID':
        status = '403';
        break;
      default:
        status = '404';
        break;
    }

    const title =
      errorCode !== 'SESSION_INVALID'
        ? errorMessage
        : intl.get({
            id: 'code-assets.components.errorPage.TheSessionHasExpiredPlease',
            defaultMessage: '会话过期，请重新登录',
          });
    return (
      <React.Fragment>
        <ConfigProvider prefix="yx-">
          <Result
            title={title}
            img={status}
            imgAlign={'left'}
            desc={this.renderDesc()}
            theme={'yunxiao'}
            size={'large'}
            extra={this.renderBtns()}
            className={'code-error-page'}
            {...others}
          />
        </ConfigProvider>
        {isModalOpen && (
          <UnfreezeIpModal
            isModalOpen={isModalOpen}
            closeModal={() => {
              this.setState({
                isModalOpen: false,
              });
            }}
            onSuccess={() => {
              window.location.reload();
            }}
          />
        )}
      </React.Fragment>
    );
  }
}
